package com.lgx.right.controller;

import java.io.PrintWriter;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lgx.common.exception.DataException;
import com.lgx.common.tree.easyui.TreeModel;
import com.lgx.common.web.Constants;
import com.lgx.common.web.Pagination;
import com.lgx.common.web.json.Json2Utils;
import com.lgx.common.web.json.JsonUtils;
import com.lgx.common.web.util.EscapeUtils;
import com.lgx.common.web.util.ListConvertToSet;
import com.lgx.right.entity.Permission;
import com.lgx.right.entity.Role;
import com.lgx.right.entity.User;
import com.lgx.right.service.IPermissionService;
import com.lgx.right.service.IRoleService;

@Controller
@RequestMapping("/role")
public class RoleController {

	@Autowired
	private IRoleService roleService;
	
	@Autowired
	private IPermissionService permissionService;

	public IRoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}

	public IPermissionService getPermissionService() {
		return permissionService;
	}

	public void setPermissionService(IPermissionService permissionService) {
		this.permissionService = permissionService;
	}
	
	@RequestMapping("/roleMgr.do")
	public String roleMgr(HttpServletRequest request,HttpServletResponse response)
	{
		return "right/role/roleMgr";
	}
	
	@RequestMapping("/list.do")
	public void list(HttpServletRequest request,HttpServletResponse response)
	{
		String pageNum = request.getParameter("page");
		String pageSize= request.getParameter("rows");
		
		Object[] params = new Object[10];
		String name = request.getParameter("name");
		if(!StringUtils.isEmpty(name))
		{
			params[0] = name;
		}
		
		if(StringUtils.isEmpty(pageSize))pageSize = Constants.PAGE_SIZE;
		if(StringUtils.isEmpty(pageNum))pageNum = Constants.FIRST_PAGE_NUM;
		
		Pagination page = this.roleService.findRolePagination(params, Integer.parseInt(pageSize), Integer.parseInt(pageNum));
		
		Json2Utils.parseJSON(page, response);
	}
	
	@RequestMapping("/init.do")
	public String init(HttpServletRequest request,HttpServletResponse response)
	{
		String type = request.getParameter("type");
		String roleId = request.getParameter("roleId");
		if(type.equals("edit")){
			//根据id查找出对应的角色名称
			Role role = this.roleService.findRoleById(Long.parseLong(roleId));
			request.setAttribute("role", role);
		}
		
		request.setAttribute("type", type);
		request.setAttribute("roleId", roleId);
		
		return "right/role/role-init";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/save.do")
	@ResponseBody
	public String save(HttpServletRequest request,HttpServletResponse response)
	{
		String name = request.getParameter("name");
		if(!StringUtils.isEmpty(name))name = EscapeUtils.unescape(name);
		String ids = request.getParameter("ids");
		List<Permission> ps = this.permissionService.findPermissionByIds(ids);
		
		String pns = "";
		
		for(Permission p : ps)
		{
			if(!StringUtils.isEmpty(pns))pns += ",";
			pns += p.getName();
		}
		
		User user = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
		
		Role role = new Role();
		
		role.setName(name);
		role.setPermissions((Set<Permission>) ListConvertToSet.convertToSet(ps));
		role.setMids(ids);
		role.setPns(pns);
		role.setCreaterId(user.getId());
		role.setCreateName(user.getUsername());
		
		try {
			this.roleService.createRole(role);
			return "1";
		} catch (DataException e) {
			e.printStackTrace();
			return "0";
		}
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/update.do")
	@ResponseBody
	public String update(HttpServletRequest request,HttpServletResponse response)
	{
		String roleId = request.getParameter("roleId");                      //接受需要授权的角色id
		Role role = this.roleService.findRoleById(Long.parseLong(roleId));   //返回需要授权的角色对象
		String name = request.getParameter("name");                          //得到角色name
		if(!StringUtils.isEmpty(name))name = EscapeUtils.unescape(name);
		String ids = request.getParameter("ids");                            //得到权限信息组
		List<Permission> ps = this.permissionService.findPermissionByIds(ids);

		String pns = "";
		
		for(Permission p : ps)
		{
			if(!StringUtils.isEmpty(pns))pns += ",";
			pns += p.getName();
		}
		
		role.setName(name);
		role.setPermissions((Set<Permission>) ListConvertToSet.convertToSet(ps));
		role.setMids(ids);
		role.setPns(pns);
		
		try {
			this.roleService.updateRole(role);
			return "1";
		} catch (DataException e) {
			e.printStackTrace();
			return "0";
		}
	}

	@RequestMapping("/delete.do")
	@ResponseBody
	public String delete(HttpServletRequest request,HttpServletResponse response)
	{
		String ids = request.getParameter("ids");
		try {
			this.roleService.deleteRoles(ids.split(","));
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}
	
	@RequestMapping("/userTree.do")
	public void userTree(HttpServletRequest request,HttpServletResponse response)
	{
		String userId = request.getParameter("userId");//接受用户id
		
		if(StringUtils.isEmpty(userId))userId = "0";
		List<TreeModel> tm = roleService.findRoleUserTreeList(Long.parseLong(userId));
		JsonUtils utils = new JsonUtils();
		String json;
		try {
			json = utils.converToJson(tm);
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.print(json);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}




